package online.foxnull2.foxmall.order.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import online.foxnull2.common.to.mq.OrderTo;
import online.foxnull2.foxmall.order.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.IOException;

@Slf4j
@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderReleaseListener {

    private final OrderService orderService;

    @Autowired
    public OrderReleaseListener(OrderService orderService) {
        Assert.notNull(orderService, "OrderService must not be null!");
        this.orderService = orderService;
    }

    @RabbitHandler
    public void orderReleaseHandle(OrderTo orderTo, Message message, Channel channel)
            throws IOException {
        log.debug("orderReleaseHandle start");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            orderService.orderReleaseHandle(orderTo);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicReject(deliveryTag, true);
        }
        log.debug("orderReleaseHandle end");
    }
}
